package by.alex.dzeshko.facebooksuperclient.service;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.async.LoadJsonObjectAsyncTask;
import by.alex.dzeshko.facebooksuperclient.async.common.ParamCallback;
import by.alex.dzeshko.facebooksuperclient.http.HttpManager;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;

public class FriendsService extends CommonService<JSONObject> implements ParamCallback<JSONObject>{
	
	public static final String ACTION_ON_ERROR = "by.alex.dzeshko.facebooksuperclient.service.FreindsService.ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.alex.dzeshko.facebooksuperclient.service.FreindsService.ACTION_ON_SUCCESS";
	
	public static final String NEXT_PAGE = "by.alex.dzeshko.facebooksuperclient.service.FreindsService.NEXT_PAGE";

	protected static final String LOG_TAG = "FriendsService";
	
	
	@Override
	protected void handleCommand(Intent intent) {
		super.handleCommand(intent);
		new LoadJsonObjectAsyncTask(this).start(requestBuilder);
	}

	@Override
	public void onSuccess(JSONObject p) {
		onHandleResponse(p);
	}
	
	@Override
	public void onError(Throwable e) {
		Log.e(LOG_TAG,e.toString());
		Intent intent = new Intent(ACTION_ON_ERROR);
		intent.putExtra(EXTRA_KEY_MESSAGE, e.toString());
		sendBroadcast(intent);
	}
	
	@Override
	protected void threadedHandleResponse(JSONObject obj) {
		if(obj.has(getString(ERROR))){
			JSONObject err;
			try {
				err = obj.getJSONObject(getString(ERROR));
				String errMessage = err.getString(getString(TYPE))+err.getString(getString(MESSAGE));
				Log.e(err.getString(getString(TYPE)),errMessage);
				onError(new Throwable(errMessage));
				return;
			} catch (JSONException e) {
				onError(e);
			}
		}
		try{
		JSONArray array = obj.getJSONArray(getString(DATA));
		List<JSONObject> list = new ArrayList<JSONObject>();
		for (int i = 0; i < array.length(); i++) {
			list.add(array.getJSONObject(i));
		}
		for (JSONObject jsonObject : list) {
			ContentValues contentValues = new ContentValues();
			contentValues.put("data", jsonObject.toString());
			getContentResolver().insert(FbContract.FriendsColumns.FRIENDS_CONTENT_URI, contentValues);
			}
		Intent intent = new Intent(ACTION_ON_SUCCESS);
		String nextPage = NO_PAGES;
		if(obj.has(getString(PAGING))){
			JSONObject paging = obj.getJSONObject(getString(PAGING));
			if(paging.has(getString(NEXT))){
				 nextPage=paging.getString(getString(NEXT));
			}
		}
		intent.putExtra(NEXT_PAGE, nextPage);
		sendBroadcast(intent);
		} catch (JSONException e) {
			onError(e);
		}
		
	}


}
